const db = uniCloud.database();
const { result, redisIpCount } = require('product-api-utils');
let dbJQL;

module.exports = {
	_before: async function () {
		// 通用预处理器
		// await redisIpCount(this);

		this.startTime = Date.now();
		const httpInfo = this.getHttpInfo();

		if (httpInfo.path !== '/getNav') {
			const body = httpInfo.body;
			if (!body) throw result(400, 'required');
			this.params = JSON.parse(body);
		}

		dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		dbJQL.setUser({
			uid: '680c9977af3a3cca857ec1b9', // uni-id-users表
			role: ['admin'] // uni-id-roles表
		});
	},

	// 获取导航列表
	getNav: async function () {
		// let xzsNav = await redis.get('mySelf:xzs-nav');
		// if (xzsNav) {
		// 	return result(0, 'success', JSON.parse(xzsNav));
		// }
		let res = await db
			.collection('product_xzs_nav')
			.field({
				createTime: false,
				orderid: false,
				state: false
			})
			.where({
				state: true
			})
			.orderBy('orderid', 'asc')
			.get();
		let arr = res.data.map((item) => {
			return {
				_id: item._id,
				classname: item.classname,
				icon: item.icon.url
			};
		});
		// redis.set('mySelf:xzs-nav', JSON.stringify(arr));
		return result(0, 'success', arr);
	},

	//获取产品列表
	getlist: async function () {
		let { navid, pageSize = 5, pageNum = 0, keyword = '' } = this.params;

		//判断是否使用的是搜索关键字
		let conditon;
		if (keyword) {
			conditon = `${new RegExp(keyword, 'i')}.test(title)`
		} else {
			if (!navid) return result(400, 'required');
			conditon = `navid == "${navid}" && checked == true`;
		}
		//查询数据库获取列表数据
		let res = await dbJQL
			.collection('product_xzs_list')
			.where(conditon)
			.field('picurl.url as picpath,title,weight,year,price,grade,pronum')
			.skip(pageNum)
			.limit(pageSize)
			.orderBy('orderid', 'asc')
			.get();

		let count = await dbJQL.collection('product_xzs_list').where(conditon).count();

		return result(0, 'success', res.data, count.total);
	},

	//获取产品详情
	detail: async function () {
		let { id } = this.params;
		if (!id) return result(400, 'required');
		let res = await dbJQL.collection('product_xzs_list').where(`_id == "${id}"`).field('picurl.url as picpath,title,weight,year,price,grade,pronum,createTime').get({
			getOne: true
		});
		return result(0, 'success', res.data);
	},

	_after: function (error, result) {
		if (error) {
			throw error; // 如果方法抛出错误，也直接抛出不处理
		}
		result.timeCost = Date.now() - this.startTime;
		return result;
	}
};
